package exchange

import (
	"github.com/garyburd/redigo/redis"
	"global/libs/structs"
	"sync"
	"time"
	"github.com/parnurzeal/gorequest"
	"github.com/ngaut/log"
	"encoding/json"
	"global/core"
	"strings"
	"global/libs/exchanges"
)

type BitZDepth struct {
	Slug 			string
	Pool 			*redis.Pool
	Symbol 			structs.Symbol
	IntervalC 		*time.Ticker
	mux 			sync.Mutex
	Client 			*gorequest.SuperAgent
}

func NewBitZDepth(slug string, pool *redis.Pool) InterfaceDepth {
	bitz := &BitZDepth{
		Pool: 		pool,
		Slug: 		slug,
		IntervalC: 	time.NewTicker(2 * time.Second),
	}

	bitz.Client = gorequest.New()

	return bitz
}

func (t *BitZDepth) NeedSymbols() bool {
	return false
}

func (t *BitZDepth) ListenAndAccept(symbol structs.Symbol) error {
	t.Symbol = symbol
	t.handler()
	for timer := range t.IntervalC.C {
		_ = timer
		go t.handler()
	}
	return nil
}

func (t *BitZDepth) handler() {
	start := time.Now()
	_, body, errs := t.Client.
		Get(core.GetBitZUrl("depth")).
		Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36").
		Query(map[string]interface{} {
			"symbol": strings.ToLower(t.Symbol.From + "_" + t.Symbol.To),
		}).
		End()
	if len(errs) > 0 {
		log.Errorf("Error: %s", errs[0])
		return
	}

	type bitzResponse struct {
		exchanges.BitzBaseResponse
		Data 		exchanges.BitzDepth 		`json:"data"`
	}

	var bitzResponseData bitzResponse
	err := json.Unmarshal([]byte(body), &bitzResponseData)
	if err != nil {
		log.Errorf("Error: symbol: %s, %s", t.Symbol.From + "_" + t.Symbol.To, err)
		return
	}

	// 处理数据
	var depths structs.Depth
	depths.Asks = bitzResponseData.Data.Asks
	depths.Bids = bitzResponseData.Data.Bids

	conn := t.Pool.Get()
	defer conn.Close()

	if err := core.SaveDepth(conn, t.Slug, t.Symbol, depths); err != nil {
		log.Errorf("Error: save depth failed, msg: %s", err)
		return
	}

	log.Infof("Get depth from bit-z complete, symbol: %s, take time: %s",
		bitzResponseData.Data.CoinPair, time.Since(start))
}
